<?php
declare(strict_types=1);

namespace DreamCat\ObjectOrm;

use Dreamcat\Class2Array\Impl\DefaultJsonValueFixer;
use Psr\Container\ContainerInterface;
use ReflectionProperty;

/**
 * -
 * @author vijay
 */
class Class2Array extends DefaultJsonValueFixer
{
    /**
     * @param ContainerInterface $container 容器
     */
    public function __construct(private ContainerInterface $container)
    {
    }

    /**
     * @return ContainerInterface 容器
     */
    public function getContainer(): ContainerInterface
    {
        return $this->container;
    }

    /**
     * @param ContainerInterface $container 容器
     */
    public function setContainer(ContainerInterface $container): void
    {
        $this->container = $container;
    }

    /** @inheritDoc */
    protected function getPropertyValue(ReflectionProperty $property, object $object): mixed
    {
        $value = parent::getPropertyValue($property, $object);
        $attrs = $property->getAttributes(OrmInfo::class);
        if ($attrs) {
            /** @var OrmInfo $info */
            $info = $attrs[0]->newInstance();
            if ($this->getContainer()->has($info->getConvert())) {
                $convert = $this->getContainer()->get($info->getConvert());
                if ($convert instanceof DataConvertInterface) {
                    $value = $convert->model2db($value);
                }
            }
        }
        return $value;
    }
}

# end of file
